import {list } from '@/api/menu.js'
// import _ from 'lodash'
import Layout from '@/layout/index.vue'
import router, { routes } from '@/router'
import { handleTree} from '@/utils/utils'
var getRouter;

const permission = {
  state:{
    sidebarRouters: []
  },
  mutations:{
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.sidebarRouters = routes
    },
  },
  actions:{
    // 生成路由
    GenerateRoutes({commit}) {
      return new Promise(resolve => {
      const sidebarRouters = routerGo()
      console.log('getRouter sidebarRouters', sidebarRouters)
      commit('SET_TOPBAR_ROUTES', sidebarRouters)
      resolve(sidebarRouters)
    })
    }
  }
}
  
// 导航到一个新的路由方法封装
function routerGo() {
  getRouter = JSON.parse(localStorage.getItem('menuList')) 
  getRouter = filterAsyncRouter(getRouter) // 过滤路由
  getRouter=getRouter.concat(routes)
  router.options.routes = getRouter; //必须在addroutes前，使用router.options.routes=XXXXX的方法手动添加
  router.addRoutes(getRouter) //动态添加路由
  console.log('getRouter',getRouter)
  global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
  return getRouter
}
//过滤路由方法封装
function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  // console.log(asyncRouterMap)
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      // console.log('route',route)
      if (route.component === 'layout') {//Layout组件特殊处理
        route.component = Layout
      } else {
        //  console.log(asyncRouterMap)
        if (!route.parentId || route.parentId.length === 0) {
          let childMenu = [], menuData =JSON.parse(JSON.stringify(route))
          menuData.parentId = route._id
          childMenu.push(menuData)
          route.children = childMenu
          route.path = ''
          route.component = Layout
          }else{
            route.component = loadView(route.component)
          }
      }
    }
    else {
      route.component = Layout
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
 function loadView(view){ // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}
export default permission